import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from 'axios'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))

  // 登录
  const login = async (loginForm) => {
    try {
      // 这里是模拟登录，实际项目中需要调用后端API
      if (loginForm.username === 'admin' && loginForm.password === 'admin123') {
        const mockToken = 'mock-token-' + Date.now()
        const mockUserInfo = {
          username: 'admin',
          nickname: '管理员',
          avatar: 'https://avatars.githubusercontent.com/u/1?v=4'
        }
        
        token.value = mockToken
        userInfo.value = mockUserInfo
        
        localStorage.setItem('token', mockToken)
        localStorage.setItem('userInfo', JSON.stringify(mockUserInfo))
        
        // 设置axios请求头
        axios.defaults.headers.common['Authorization'] = `Bearer ${mockToken}`
        
        return Promise.resolve()
      } else {
        return Promise.reject(new Error('用户名或密码错误'))
      }
    } catch (error) {
      return Promise.reject(error)
    }
  }

  // 登出
  const logout = () => {
    token.value = ''
    userInfo.value = {}
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    delete axios.defaults.headers.common['Authorization']
  }

  return {
    token,
    userInfo,
    login,
    logout
  }
})
